package com.quick.im.client.strategy;

import com.quick.im.client.abstracts.AbsMessageStrategy;
import com.quick.im.client.handler.NettyClientHandler;
import com.quick.im.client.service.MessageRecordOfflineServiceImpl;
import com.quick.im.client.service.MessageRecordServiceImpl;
import com.quick.im.common.constant.ImRedisKey;
import com.quick.im.common.entity.domian.MessageRecord;
import com.quick.im.common.entity.domian.MessageRecordOffline;
import com.quick.im.common.entity.message.MessageInfo;
import com.quick.im.common.enums.GlobalExceptionEnum;
import com.quick.im.common.util.RedisUtils;
import jakarta.websocket.Session;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.quick.im.common.constant.MessageStatusConstant.MESSAGE_NOT_RECEIVED;

/**
 * 文字消息处理类
 */
@Service
@Slf4j
public class TextMessageStrategy extends AbsMessageStrategy {

    @Setter(onMethod_ = @Autowired)
    private NettyClientHandler nettyClientHandler;
    @Setter(onMethod_ = @Autowired)
    private MessageRecordServiceImpl messageRecordService;
    @Setter(onMethod_ = @Autowired)
    private MessageRecordOfflineServiceImpl messageRecordOfflineService;
    @Override
    protected void sendMessage(MessageInfo messageInfo, Session session) {
        nettyClientHandler.sendMessage(messageInfo);
    }

    /**
     * 校验用户是否在线
     * @param messageInfo
     * @param session
     * @throws Exception
     */
    @Override
    protected void sendMessageBefore(MessageInfo messageInfo, Session session) throws Exception {
        // 保存到消息记录表
        Object o = RedisUtils.get(ImRedisKey.USER_CONNECT_INFO + messageInfo.getSendUid());
        MessageRecord messageRecord = new MessageRecord();
        BeanUtils.copyProperties(messageInfo, messageRecord);
        messageRecord.setMessageStatus(MESSAGE_NOT_RECEIVED);
        messageRecordService.saveMessageToOne(messageRecord);
        // 判断用户是否在线
        if (o == null){
            log.info("消息接收用户：{}--------->离线",messageInfo.getReceiveUid());
            MessageRecordOffline messageRecordOffline = new MessageRecordOffline();
            BeanUtils.copyProperties(messageInfo, messageRecordOffline);
            messageRecordOffline.setMessageStatus(MESSAGE_NOT_RECEIVED);
            messageRecordOfflineService.save(messageRecordOffline);
            // 用户离线不需要走后续流程 通过异常来阻断后续的流程  用户上线时会从离线消息表获取离线消息  推送给用户
            log.warn(GlobalExceptionEnum.USER_OFFLINE.getInfo());
            throw new Exception(GlobalExceptionEnum.USER_OFFLINE.getCode());
        }
    }

    @Override
    protected void sendMessageAfter(MessageInfo messageInfo, Session session) {

    }
}
